// 套利相关的Mock数据

// 交易所类型枚举
export enum ExchangeType {
  CEX = 'CEX',
  DEX = 'DEX'
}

// 交易所信息
export interface ExchangeInfo {
  id: string;
  name: string;
  type: ExchangeType;
  network?: string; // 对于DEX
  fees: {
    maker: number;
    taker: number;
    withdrawal?: number;
    gas?: number; // 对于DEX
  };
  characteristics: {
    liquidity: 'high' | 'medium' | 'low';
    slippage: 'low' | 'medium' | 'high';
    speed: 'fast' | 'medium' | 'slow';
    reliability: 'high' | 'medium' | 'low';
  };
  advantages: string[];
  disadvantages: string[];
}

// 套利策略类型
export enum ArbitrageStrategy {
  CEX_CEX = 'CEX_CEX',
  DEX_DEX = 'DEX_DEX',
  CEX_DEX = 'CEX_DEX'
}

// 交易所数据
export const exchangeDatabase: ExchangeInfo[] = [
  {
    id: 'binance',
    name: 'Binance',
    type: ExchangeType.CEX,
    fees: {
      maker: 0.001,
      taker: 0.001,
      withdrawal: 0.0005
    },
    characteristics: {
      liquidity: 'high',
      slippage: 'low',
      speed: 'fast',
      reliability: 'high'
    },
    advantages: [
      '全球最大交易量',
      '极低滑点',
      '丰富交易对',
      'API稳定性好',
      '深度充足'
    ],
    disadvantages: [
      '监管风险',
      'KYC要求严格',
      '可能限制提现',
      '竞争激烈价差小'
    ]
  },
  {
    id: 'okx',
    name: 'OKX',
    type: ExchangeType.CEX,
    fees: {
      maker: 0.0008,
      taker: 0.001,
      withdrawal: 0.0005
    },
    characteristics: {
      liquidity: 'high',
      slippage: 'low',
      speed: 'fast',
      reliability: 'high'
    },
    advantages: [
      '期货产品丰富',
      '亚洲市场优势',
      '手续费较低',
      '支持多种衍生品'
    ],
    disadvantages: [
      '部分地区受限',
      '流动性略低于Binance',
      'UI相对复杂'
    ]
  },
  {
    id: 'bybit',
    name: 'Bybit',
    type: ExchangeType.CEX,
    fees: {
      maker: 0.0001,
      taker: 0.0006,
      withdrawal: 0.0005
    },
    characteristics: {
      liquidity: 'medium',
      slippage: 'low',
      speed: 'fast',
      reliability: 'high'
    },
    advantages: [
      'Maker费率极低',
      '期货交易专业',
      '用户体验好',
      'API响应快'
    ],
    disadvantages: [
      '现货流动性一般',
      '交易对相对较少',
      '主要面向衍生品'
    ]
  },
  {
    id: 'backpack',
    name: 'Backpack',
    type: ExchangeType.CEX,
    fees: {
      maker: 0.0002,
      taker: 0.0005,
      withdrawal: 0.0003
    },
    characteristics: {
      liquidity: 'low',
      slippage: 'medium',
      speed: 'fast',
      reliability: 'medium'
    },
    advantages: [
      '新兴交易所价差大',
      '手续费低',
      '技术创新',
      'Solana生态支持'
    ],
    disadvantages: [
      '流动性不足',
      '交易对有限',
      '历史较短',
      '深度相对较浅'
    ]
  },
  {
    id: 'uniswap',
    name: 'Uniswap V3',
    type: ExchangeType.DEX,
    network: 'Ethereum',
    fees: {
      maker: 0.003, // 0.3% pool fee
      taker: 0.003,
      gas: 50 // USD equivalent
    },
    characteristics: {
      liquidity: 'high',
      slippage: 'medium',
      speed: 'slow',
      reliability: 'high'
    },
    advantages: [
      '去中心化',
      '无KYC',
      '流动性挖矿收益',
      '支持长尾资产',
      '集中流动性'
    ],
    disadvantages: [
      '无常损失风险',
      'Gas费用高',
      '滑点较大',
      'MEV攻击风险',
      '确认时间长'
    ]
  },
  {
    id: 'pancakeswap',
    name: 'PancakeSwap',
    type: ExchangeType.DEX,
    network: 'BSC',
    fees: {
      maker: 0.0025, // 0.25% fee
      taker: 0.0025,
      gas: 0.5 // USD equivalent
    },
    characteristics: {
      liquidity: 'medium',
      slippage: 'medium',
      speed: 'medium',
      reliability: 'medium'
    },
    advantages: [
      'Gas费用低',
      '确认速度快',
      '流动性挖矿',
      '生态系统完整'
    ],
    disadvantages: [
      '中心化程度高',
      '跨链资产风险',
      'MEV问题',
      '监管不确定性'
    ]
  },
  {
    id: 'raydium',
    name: 'Raydium',
    type: ExchangeType.DEX,
    network: 'Solana',
    fees: {
      maker: 0.0025,
      taker: 0.0025,
      gas: 0.01 // SOL
    },
    characteristics: {
      liquidity: 'medium',
      slippage: 'low',
      speed: 'fast',
      reliability: 'medium'
    },
    advantages: [
      '极低Gas费',
      '高TPS',
      '与Serum整合',
      '快速确认'
    ],
    disadvantages: [
      '网络稳定性问题',
      '生态相对较小',
      '跨链复杂',
      '技术风险'
    ]
  }
];

// 实时价格监控数据
export interface PriceMonitorData {
  symbol: string;
  exchanges: {
    [exchange: string]: {
      price: number;
      bid: number;  // 买一价
      ask: number;  // 卖一价
      timestamp: number;
      volume24h: number;
      depth: {
        bidQty: number;  // 买一数量
        askQty: number;  // 卖一数量
      };
      type: ExchangeType;
      network?: string;
    };
  };
  priceDiff: {
    maxDiff: number;
    maxDiffPercent: number;
    highestExchange: string;
    lowestExchange: string;
    realSpread: number;  // 真实套利空间（考虑买卖价差）
    spreadPercent: number;
  };
  lastUpdate: number;
}

// 套利机会数据
export interface ArbitrageOpportunity {
  id: string;
  symbol: string;
  strategy: ArbitrageStrategy; // 套利策略类型
  highExchange: string;
  lowExchange: string;
  highPrice: number;
  lowPrice: number;
  // 更精确的价格数据
  highAsk: number;      // 高价交易所卖一价（开空用）
  lowBid: number;       // 低价交易所买一价（开多用）
  priceDiff: number;
  diffPercent: number;
  // 真实套利数据
  realSpread: number;   // 真实可套利价差 (highBid - lowAsk)
  realSpreadPercent: number;
  expectedSlippage: number; // 预期滑点
  totalFees: number;    // 总手续费
  gasEstimate?: number; // Gas费用估算（DEX）
  impermanentLossRisk?: number; // 无常损失风险（DEX）
  netProfitPotential: number; // 净利润潜力
  executionTime: number; // 预计执行时间（秒）
  startTime: number;
  duration: number;
  status: 'active' | 'expired' | 'executed';
  riskLevel: 'low' | 'medium' | 'high';
  minTradeAmount: number;
  maxTradeAmount: number;
  // 平仓策略
  convergenceTarget: number; // 目标收敛价格
  stopLoss: number;     // 止损价差
  takeProfit: number;   // 止盈价差
  // 策略特定风险
  risks: string[];
  advantages: string[];
}

// 套利操作记录
export interface ArbitrageOperation {
  id: string;
  symbol: string;
  strategy: ArbitrageStrategy;
  type: 'manual' | 'auto';
  status: 'pending' | 'active' | 'completed' | 'failed';
  startTime: number;
  endTime?: number;
  positions: {
    exchange: string;
    exchangeType: ExchangeType;
    side: 'long' | 'short';
    entryPrice: number;
    entrySlippage: number;  // 入场滑点
    exitPrice?: number;
    exitSlippage?: number;  // 出场滑点
    quantity: number;
    pnl?: number;
    fees: number;           // 该仓位手续费
    gasUsed?: number;       // Gas使用量（DEX）
    impermanentLoss?: number; // 无常损失（DEX）
  }[];
  convergencePrice?: number;  // 实际收敛价格
  totalPnl?: number;
  totalFees: number;
  totalGasCost?: number;      // 总Gas成本
  totalImpermanentLoss?: number; // 总无常损失
  netProfit?: number;
  profitRate?: number;    // 收益率
  executionTimeActual?: number; // 实际执行时间
}

// 实时价格监控Mock数据（包含CEX和DEX）
export const mockPriceMonitor: PriceMonitorData[] = [
  {
    symbol: 'BTC/USDT',
    exchanges: {
      'Binance': {
        price: 43250.50,
        bid: 43248.20,
        ask: 43252.80,
        timestamp: Date.now() - 1000,
        volume24h: 125000000,
        depth: { bidQty: 2.5, askQty: 1.8 },
        type: ExchangeType.CEX
      },
      'OKX': {
        price: 43275.80,
        bid: 43273.50,
        ask: 43278.10,
        timestamp: Date.now() - 2000,
        volume24h: 98000000,
        depth: { bidQty: 1.9, askQty: 2.1 },
        type: ExchangeType.CEX
      },
      'Bybit': {
        price: 43265.20,
        bid: 43262.90,
        ask: 43267.50,
        timestamp: Date.now() - 1500,
        volume24h: 87000000,
        depth: { bidQty: 3.2, askQty: 1.5 },
        type: ExchangeType.CEX
      },
      'Backpack': {
        price: 43280.00,
        bid: 43277.70,
        ask: 43282.30,
        timestamp: Date.now() - 500,
        volume24h: 45000000,
        depth: { bidQty: 1.2, askQty: 1.8 },
        type: ExchangeType.CEX
      }
    },
    priceDiff: {
      maxDiff: 29.50,
      maxDiffPercent: 0.068,
      highestExchange: 'Backpack',
      lowestExchange: 'Binance',
      realSpread: 25.50, // Backpack买一 - Binance卖一
      spreadPercent: 0.059
    },
    lastUpdate: Date.now()
  },
  {
    symbol: 'ETH/USDT',
    exchanges: {
      'Binance': {
        price: 2580.45,
        bid: 2579.20,
        ask: 2581.70,
        timestamp: Date.now() - 800,
        volume24h: 89000000,
        depth: { bidQty: 15.5, askQty: 12.8 },
        type: ExchangeType.CEX
      },
      'Uniswap': {
        price: 2595.30,
        bid: 2590.15, // 模拟买入价格
        ask: 2600.45, // 模拟卖出价格
        timestamp: Date.now() - 1200,
        volume24h: 45000000,
        depth: { bidQty: 8.2, askQty: 6.1 },
        type: ExchangeType.DEX,
        network: 'Ethereum'
      },
      'PancakeSwap': {
        price: 2588.90,
        bid: 2585.75,
        ask: 2592.05,
        timestamp: Date.now() - 600,
        volume24h: 32000000,
        depth: { bidQty: 12.1, askQty: 9.5 },
        type: ExchangeType.DEX,
        network: 'BSC'
      }
    },
    priceDiff: {
      maxDiff: 14.85,
      maxDiffPercent: 0.058,
      highestExchange: 'Uniswap',
      lowestExchange: 'Binance',
      realSpread: 8.45, // Uniswap买一 - Binance卖一
      spreadPercent: 0.033
    },
    lastUpdate: Date.now()
  }
];

// 更新的套利机会Mock数据（包含不同策略）
export const mockArbitrageOpportunities: ArbitrageOpportunity[] = [
  {
    id: 'arb_001',
    symbol: 'BTC/USDT',
    strategy: ArbitrageStrategy.CEX_CEX,
    highExchange: 'Backpack',
    lowExchange: 'Binance',
    highPrice: 43280.00,
    lowPrice: 43250.50,
    highAsk: 43282.30,
    lowBid: 43248.20,
    priceDiff: 29.50,
    diffPercent: 0.068,
    realSpread: 25.50,
    realSpreadPercent: 0.059,
    expectedSlippage: 3.20,
    totalFees: 8.65,
    netProfitPotential: 13.65,
    executionTime: 5, // 5秒执行
    startTime: Date.now() - 45000,
    duration: 45,
    status: 'active',
    riskLevel: 'low',
    minTradeAmount: 1000,
    maxTradeAmount: 50000,
    convergenceTarget: 43265.25,
    stopLoss: 5.0,
    takeProfit: 2.0,
    risks: [
      '账户冻结风险',
      'API限流风险',
      '价格快速收敛'
    ],
    advantages: [
      '无无常损失',
      '执行速度快',
      '滑点可控',
      '流动性充足'
    ]
  },
  {
    id: 'arb_002',
    symbol: 'ETH/USDT',
    strategy: ArbitrageStrategy.CEX_DEX,
    highExchange: 'Uniswap',
    lowExchange: 'Binance',
    highPrice: 2595.30,
    lowPrice: 2580.45,
    highAsk: 2600.45,
    lowBid: 2579.20,
    priceDiff: 14.85,
    diffPercent: 0.058,
    realSpread: 8.45,
    realSpreadPercent: 0.033,
    expectedSlippage: 12.50,
    totalFees: 15.80,
    gasEstimate: 45.00, // Gas费用
    impermanentLossRisk: 8.20,
    netProfitPotential: -62.05, // 负收益！
    executionTime: 180, // 3分钟执行
    startTime: Date.now() - 28000,
    duration: 28,
    status: 'active',
    riskLevel: 'high',
    minTradeAmount: 2000,
    maxTradeAmount: 20000,
    convergenceTarget: 2587.88,
    stopLoss: 25.0,
    takeProfit: 5.0,
    risks: [
      '无常损失风险',
      'Gas费用高昂',
      'MEV攻击风险',
      '网络拥堵风险',
      '智能合约风险'
    ],
    advantages: [
      '价差相对较大',
      '去中心化',
      '无KYC要求',
      '支持长尾资产'
    ]
  },
  {
    id: 'arb_003',
    symbol: 'SOL/USDT',
    strategy: ArbitrageStrategy.DEX_DEX,
    highExchange: 'Raydium',
    lowExchange: 'PancakeSwap',
    highPrice: 99.85,
    lowPrice: 98.95,
    highAsk: 100.20,
    lowBid: 98.70,
    priceDiff: 0.90,
    diffPercent: 0.091,
    realSpread: 1.50,
    realSpreadPercent: 0.152,
    expectedSlippage: 2.80,
    totalFees: 5.10,
    gasEstimate: 0.05, // SOL网络Gas费低
    impermanentLossRisk: 3.50,
    netProfitPotential: -10.05, // 需要跨链，成本高
    executionTime: 300, // 5分钟（跨链时间）
    startTime: Date.now() - 15000,
    duration: 15,
    status: 'active',
    riskLevel: 'high',
    minTradeAmount: 500,
    maxTradeAmount: 10000,
    convergenceTarget: 99.40,
    stopLoss: 2.0,
    takeProfit: 0.50,
    risks: [
      '跨链桥接风险',
      '双重无常损失',
      '流动性不足风险',
      '网络稳定性风险',
      '套利窗口短'
    ],
    advantages: [
      '价差相对较大',
      '竞争相对较少',
      '去中心化',
      'Gas费用低（Solana）'
    ]
  }
];

// 策略分析函数
export const getStrategyAnalysis = (strategy: ArbitrageStrategy) => {
  switch (strategy) {
    case ArbitrageStrategy.CEX_CEX:
      return {
        name: 'CEX-CEX套利',
        riskLevel: 'low',
        profitPotential: 'low',
        executionComplexity: 'low',
        capitalRequirement: 'medium',
        recommendedFor: '稳健型投资者',
        pros: [
          '无无常损失风险',
          '执行速度快（秒级）',
          '滑点可控',
          '手续费相对较低',
          '流动性充足',
          'API稳定性好'
        ],
        cons: [
          '监管风险',
          '需要KYC',
          '价差较小',
          '竞争激烈',
          '需要多交易所资金'
        ],
        bestPractices: [
          '选择流动性高的主流交易所',
          '监控API限流',
          '分散资金到多个交易所',
          '使用专业交易工具'
        ]
      };
    
    case ArbitrageStrategy.DEX_DEX:
      return {
        name: 'DEX-DEX套利',
        riskLevel: 'high',
        profitPotential: 'medium',
        executionComplexity: 'high',
        capitalRequirement: 'high',
        recommendedFor: '专业DeFi用户',
        pros: [
          '去中心化',
          '无KYC要求',
          '价差相对较大',
          '支持长尾资产',
          '可以获得流动性挖矿收益'
        ],
        cons: [
          '无常损失风险',
          'Gas费用高',
          'MEV攻击风险',
          '执行时间长',
          '跨链复杂性',
          '智能合约风险'
        ],
        bestPractices: [
          '选择同一网络的DEX',
          '避免跨链操作',
          '监控Gas价格',
          '使用MEV保护工具',
          '计算无常损失'
        ]
      };
    
    case ArbitrageStrategy.CEX_DEX:
      return {
        name: 'CEX-DEX套利',
        riskLevel: 'high',
        profitPotential: 'high',
        executionComplexity: 'high',
        capitalRequirement: 'high',
        recommendedFor: '资深量化交易员',
        pros: [
          '价差最大',
          '结构性套利机会',
          '竞争相对较少',
          'alpha收益潜力大'
        ],
        cons: [
          '执行复杂度高',
          'Gas费用不可预测',
          '跨生态系统风险',
          '时间成本高',
          '技术门槛高',
          '多重风险叠加'
        ],
        bestPractices: [
          '优先选择Layer2 DEX',
          '预留充足Gas费',
          '使用闪电贷减少资金需求',
          '建立完善的风控系统',
          '实时监控多个维度'
        ]
      };
  }
};

// 计算真实套利空间的函数
export const calculateRealArbitrageSpread = (monitor: PriceMonitorData) => {
  const exchanges = Object.keys(monitor.exchanges);
  let maxBid = -Infinity;
  let minAsk = Infinity;
  let maxBidExchange = '';
  let minAskExchange = '';
  
  exchanges.forEach(exchange => {
    const data = monitor.exchanges[exchange];
    if (data.bid > maxBid) {
      maxBid = data.bid;
      maxBidExchange = exchange;
    }
    if (data.ask < minAsk) {
      minAsk = data.ask;
      minAskExchange = exchange;
    }
  });
  
  const realSpread = maxBid - minAsk;
  const spreadPercent = (realSpread / minAsk) * 100;
  
  return {
    realSpread,
    spreadPercent,
    highestBidExchange: maxBidExchange,
    lowestAskExchange: minAskExchange,
    maxBid,
    minAsk
  };
};

// 计算平仓价格的函数
export const calculateConvergencePrice = (
  highPrice: number, 
  lowPrice: number, 
  method: 'weighted' | 'simple' | 'volume' = 'weighted'
): number => {
  switch (method) {
    case 'simple':
      return (highPrice + lowPrice) / 2;
    case 'volume':
      return highPrice * 0.4 + lowPrice * 0.6;
    case 'weighted':
    default:
      return highPrice * 0.45 + lowPrice * 0.55;
  }
};

// 实时更新价格监控数据的函数
export const updatePriceMonitor = () => {
  mockPriceMonitor.forEach(monitor => {
    Object.keys(monitor.exchanges).forEach(exchange => {
      const exchangeData = monitor.exchanges[exchange];
      const basePrice = exchangeData.price;
      const fluctuation = (Math.random() - 0.5) * 0.002;
      const newPrice = basePrice * (1 + fluctuation);
      
      // DEX有更大的价差
      const spreadMultiplier = exchangeData.type === ExchangeType.DEX ? 3 : 1;
      const spread = newPrice * (0.0001 + Math.random() * 0.0004) * spreadMultiplier;
      
      exchangeData.price = newPrice;
      exchangeData.bid = newPrice - spread / 2;
      exchangeData.ask = newPrice + spread / 2;
      exchangeData.timestamp = Date.now();
    });
    
    const realData = calculateRealArbitrageSpread(monitor);
    monitor.priceDiff.realSpread = realData.realSpread;
    monitor.priceDiff.spreadPercent = realData.spreadPercent;
    monitor.priceDiff.highestExchange = realData.highestBidExchange;
    monitor.priceDiff.lowestExchange = realData.lowestAskExchange;
    
    const prices = Object.values(monitor.exchanges).map(e => e.price);
    const maxPrice = Math.max(...prices);
    const minPrice = Math.min(...prices);
    monitor.priceDiff.maxDiff = maxPrice - minPrice;
    monitor.priceDiff.maxDiffPercent = (maxPrice - minPrice) / minPrice * 100;
    
    monitor.lastUpdate = Date.now();
  });
};

// 更新套利机会
export const updateArbitrageOpportunities = () => {
  mockArbitrageOpportunities.forEach(opp => {
    if (opp.status === 'active') {
      opp.duration = Math.floor((Date.now() - opp.startTime) / 1000);
      
      // 不同策略的时间衰减不同
      let timeDecayRate = 0.5;
      if (opp.strategy === ArbitrageStrategy.CEX_CEX) {
        timeDecayRate = 0.8; // CEX套利衰减更快
      } else if (opp.strategy === ArbitrageStrategy.DEX_DEX) {
        timeDecayRate = 0.3; // DEX套利持续时间较长
      }
      
      const timeDecay = Math.min(opp.duration / 120, timeDecayRate);
      const basePotential = opp.realSpread - opp.expectedSlippage - opp.totalFees;
      const gasAndILCost = (opp.gasEstimate || 0) + (opp.impermanentLossRisk || 0);
      
      opp.netProfitPotential = Math.max(
        -gasAndILCost, 
        basePotential - gasAndILCost - timeDecay * 2
      );
      
      if (opp.duration > 120 || (opp.netProfitPotential <= 0 && opp.strategy === ArbitrageStrategy.CEX_CEX)) {
        opp.status = 'expired';
      }
    }
  });
};

// 套利配置 - 重新设计为策略特定配置
export interface BaseArbitrageConfig {
  symbol: string;
  enabled: boolean;
  autoExecute: boolean;
  minProfitUSD: number;     // 最小利润金额（美元）
  maxPositionUSD: number;   // 最大仓位（美元）
  riskLevel: 'conservative' | 'moderate' | 'aggressive';
  // 通用风险控制
  maxHoldingMinutes: number;  // 最大持仓时间
  stopLossPercent: number;    // 止损百分比
  takeProfitPercent: number;  // 止盈百分比
}

// CEX-CEX 特定配置
export interface CEXArbitrageConfig extends BaseArbitrageConfig {
  strategy: 'CEX_CEX';
  // CEX特定参数
  exchanges: {
    primary: string[];      // 主要交易所
    secondary: string[];    // 备选交易所
  };
  leverage: {
    enabled: boolean;
    maxLeverage: number;
    marginRatio: number;    // 保证金比例
  };
  slippage: {
    maxSlippagePercent: number;  // 最大滑点容忍
    executionSpeedMs: number;    // 执行速度要求
  };
  fees: {
    makerFeePercent: number;
    takerFeePercent: number;
    withdrawalFeeUSD: number;
  };
  // 资金管理
  balanceManagement: {
    minBalanceUSD: number;       // 最小余额要求
    rebalanceThreshold: number;  // 再平衡阈值
    autoRebalance: boolean;
  };
}

// DEX-DEX 特定配置
export interface DEXArbitrageConfig extends BaseArbitrageConfig {
  strategy: 'DEX_DEX';
  // DEX特定参数
  networks: {
    primary: string[];      // 主要网络 (Ethereum, BSC, Polygon等)
    secondary: string[];    // 备选网络
  };
  dexes: {
    [network: string]: string[];  // 每个网络的DEX列表
  };
  gas: {
    maxGasPriceGwei: number;     // 最大Gas价格
    maxGasLimitUSD: number;      // 最大Gas费用限制
    priorityFeeGwei: number;     // 优先费用
    speedMode: 'slow' | 'standard' | 'fast' | 'instant';
  };
  slippage: {
    maxSlippagePercent: number;  // DEX滑点更大
    minLiquidityUSD: number;     // 最小流动性要求
    impermanentLoss: {
      maxRiskPercent: number;    // 最大无常损失风险
      monitoringEnabled: boolean;
    };
  };
  // 跨链桥配置
  bridging: {
    enabled: boolean;
    preferredBridges: string[];
    maxBridgeTimeMinutes: number;
    maxBridgeFeePercent: number;
  };
}

// CEX-DEX 混合配置
export interface HybridArbitrageConfig extends BaseArbitrageConfig {
  strategy: 'CEX_DEX';
  // 混合策略参数
  cexExchanges: string[];
  dexNetworks: {
    [network: string]: string[];  // 网络->DEX映射
  };
  // 复合风险参数
  complexRisks: {
    maxCombinedSlippage: number;     // 最大组合滑点
    maxGasImpactPercent: number;     // Gas费用影响上限
    maxImpermanentLossPercent: number; // 无常损失上限
    maxExecutionTimeMinutes: number;   // 最大执行时间
  };
  // 优先级配置
  executionPriority: {
    cexFirst: boolean;               // CEX优先执行
    gasOptimization: boolean;        // Gas优化
    slippageOptimization: boolean;   // 滑点优化
  };
  // 资金桥接
  fundBridging: {
    enabled: boolean;
    autobridge: boolean;
    maxBridgeWaitMinutes: number;
  };
}

// 统一配置类型
export type ArbitrageConfig = CEXArbitrageConfig | DEXArbitrageConfig | HybridArbitrageConfig;

// 配置模板 - 真实的专业套利配置
export const mockArbitrageConfigs: ArbitrageConfig[] = [
  // BTC CEX-CEX 保守策略
  {
    strategy: 'CEX_CEX',
    symbol: 'BTC/USDT',
    enabled: true,
    autoExecute: true,
    minProfitUSD: 25,        // BTC套利最小25美元
    maxPositionUSD: 100000,  // 10万美元大仓位
    riskLevel: 'conservative',
    maxHoldingMinutes: 15,   // CEX套利15分钟内完成
    stopLossPercent: 0.3,    // 0.3%止损
    takeProfitPercent: 0.8,  // 0.8%止盈
    exchanges: {
      primary: ['Binance', 'OKX', 'Bybit'],
      secondary: ['Backpack', 'Coinbase', 'Kraken']
    },
    leverage: {
      enabled: true,
      maxLeverage: 3,        // 3倍杠杆
      marginRatio: 0.4       // 40%保证金
    },
    slippage: {
      maxSlippagePercent: 0.05,  // 0.05%最大滑点
      executionSpeedMs: 3000     // 3秒内执行
    },
    fees: {
      makerFeePercent: 0.02,
      takerFeePercent: 0.04,
      withdrawalFeeUSD: 25
    },
    balanceManagement: {
      minBalanceUSD: 50000,
      rebalanceThreshold: 0.7,
      autoRebalance: true
    }
  },
  
  // ETH DEX-DEX 激进策略
  {
    strategy: 'DEX_DEX',
    symbol: 'ETH/USDT',
    enabled: true,
    autoExecute: false,      // 手动执行高风险策略
    minProfitUSD: 80,        // DEX套利需要更高利润覆盖Gas
    maxPositionUSD: 25000,   // 较小仓位控制风险
    riskLevel: 'aggressive',
    maxHoldingMinutes: 120,  // DEX套利可能需要2小时
    stopLossPercent: 2.0,    // 2%止损（DEX风险更大）
    takeProfitPercent: 5.0,  // 5%止盈
    networks: {
      primary: ['Ethereum', 'Arbitrum'],
      secondary: ['Polygon', 'BSC', 'Optimism']
    },
    dexes: {
      'Ethereum': ['Uniswap V3', 'SushiSwap', 'Curve'],
      'Arbitrum': ['Uniswap V3', 'Balancer', 'Camelot'],
      'Polygon': ['QuickSwap', 'SushiSwap'],
      'BSC': ['PancakeSwap', 'Biswap'],
      'Optimism': ['Uniswap V3', 'Velodrome']
    },
    gas: {
      maxGasPriceGwei: 50,     // 最大50 Gwei
      maxGasLimitUSD: 45,      // Gas费用不超过45美元
      priorityFeeGwei: 2,
      speedMode: 'fast'
    },
    slippage: {
      maxSlippagePercent: 0.8,  // DEX可接受更大滑点
      minLiquidityUSD: 500000,  // 最小50万美元流动性
      impermanentLoss: {
        maxRiskPercent: 1.5,    // 最大1.5%无常损失
        monitoringEnabled: true
      }
    },
    bridging: {
      enabled: true,
      preferredBridges: ['Stargate', 'Synapse', 'Hop'],
      maxBridgeTimeMinutes: 30,
      maxBridgeFeePercent: 0.3
    }
  },
  
  // SOL CEX-DEX 混合策略
  {
    strategy: 'CEX_DEX',
    symbol: 'SOL/USDT',
    enabled: false,          // 默认关闭高风险策略
    autoExecute: false,
    minProfitUSD: 120,       // 混合策略需要更高利润
    maxPositionUSD: 15000,
    riskLevel: 'moderate',
    maxHoldingMinutes: 45,
    stopLossPercent: 1.5,
    takeProfitPercent: 3.5,
    cexExchanges: ['Binance', 'OKX', 'Backpack'],
    dexNetworks: {
      'Solana': ['Raydium', 'Orca', 'Jupiter'],
      'Ethereum': ['Uniswap V3', 'SushiSwap']
    },
    complexRisks: {
      maxCombinedSlippage: 1.2,      // 最大组合滑点1.2%
      maxGasImpactPercent: 0.8,      // Gas影响不超过0.8%
      maxImpermanentLossPercent: 2.0, // 无常损失不超过2%
      maxExecutionTimeMinutes: 45    // 最大45分钟执行
    },
    executionPriority: {
      cexFirst: true,                // CEX优先执行
      gasOptimization: true,
      slippageOptimization: true
    },
    fundBridging: {
      enabled: true,
      autobridge: false,             // 手动桥接资金
      maxBridgeWaitMinutes: 60
    }
  }
];

export const mockArbitrageOperations: ArbitrageOperation[] = [
  {
    id: 'op_001',
    symbol: 'BTC/USDT',
    strategy: ArbitrageStrategy.CEX_CEX,
    type: 'auto',
    status: 'completed',
    startTime: Date.now() - 300000,
    endTime: Date.now() - 240000,
    positions: [
      {
        exchange: 'OKX',
        exchangeType: ExchangeType.CEX,
        side: 'short',
        entryPrice: 43290.00,
        entrySlippage: 2.50,
        exitPrice: 43265.25,
        exitSlippage: 1.80,
        quantity: 0.1,
        pnl: 2.48,
        fees: 4.32
      },
      {
        exchange: 'Binance',
        exchangeType: ExchangeType.CEX,
        side: 'long',
        entryPrice: 43245.00,
        entrySlippage: 1.80,
        exitPrice: 43265.25,
        exitSlippage: 2.10,
        quantity: 0.1,
        pnl: 2.03,
        fees: 4.33
      }
    ],
    convergencePrice: 43265.25,
    totalPnl: 4.51,
    totalFees: 8.65,
    netProfit: -4.14,
    profitRate: -0.01,
    executionTimeActual: 8
  },
  {
    id: 'op_002',
    symbol: 'ETH/USDT',
    strategy: ArbitrageStrategy.CEX_DEX,
    type: 'manual',
    status: 'active',
    startTime: Date.now() - 120000,
    positions: [
      {
        exchange: 'Uniswap',
        exchangeType: ExchangeType.DEX,
        side: 'short',
        entryPrice: 2590.00,
        entrySlippage: 15.95,
        quantity: 1.0,
        pnl: -2.20,
        fees: 7.77, // 0.3% pool fee
        gasUsed: 42.50,
        impermanentLoss: 3.20
      },
      {
        exchange: 'Binance',
        exchangeType: ExchangeType.CEX,
        side: 'long',
        entryPrice: 2575.50,
        entrySlippage: 1.85,
        quantity: 1.0,
        pnl: 3.40,
        fees: 2.58
      }
    ],
    totalPnl: 1.20,
    totalFees: 10.35,
    totalGasCost: 42.50,
    totalImpermanentLoss: 3.20,
    netProfit: -55.85,
    profitRate: -2.16
  }
];